package tat.domain;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;

import tat.exception.ObjectAlreadyExistsException;
import tat.util.Validate;
import tat2.TATClass;

public class TatClass extends Observable{

    private String name;

    private Map<String, TatAttribute> atts = new HashMap<String, TatAttribute>();

    public TatClass(final String name) {
        Validate.notNull(name, "Name must not be null.");

        this.name = name;
    }

    public TatClass(TATClass legacyTatClass) {
    	this.name = legacyTatClass.getName();
    }

	public String name() {
        return name;
    }

	public void changeName(String newName){
		this.name = newName;
		this.setChanged();
		this.notifyObservers();
	}

    @Override
	public String toString() {
        String texto = "\t" + name + "\n";
    	Collection<TatAttribute> attributes = atts.values();
    	if(! attributes.isEmpty() ){
    		texto = texto + "\t\tATTRIBUTES\n";
    		for(TatAttribute at : attributes){
        		texto = texto + "\t\t\t" + at.name() + "\n";
        	}
    	}
        return texto;
    }

    public String toXML() {
    	String texto = "\t<class> " + name + "\n";
    	Collection<TatAttribute> attributes = atts.values();
    	for(TatAttribute at : attributes){
    		texto = texto + "\t\t<attribute>" + at.name() + "</attribute>\n";
    	}
    	texto = texto + "\t</class>\n";
        return texto;
    }

	public void addAttribute(String attName) throws ObjectAlreadyExistsException {
		if (atts.containsKey(attName)) {
			throw new ObjectAlreadyExistsException("Attribute already exists.");
		}

		atts.put(attName, new TatAttribute(attName));
	}

	public TatAttribute[] attributes() {
		return atts.values().toArray(new TatAttribute[atts.size()]);
	}

	public void renameAttribute(String oldAttributeName, String newAttributeName) {
		TatAttribute attToRename = atts.remove(oldAttributeName);

		if (attToRename != null) {
			attToRename.rename(newAttributeName);

			atts.put(newAttributeName, attToRename);
		}
	}

	public void removeAttribute(String attName) {
		atts.remove(attName);
	}

}
